//
//  ProfileLoginControllerViewController.m
//  QSBK
//
//  Created by Eric Wang on 4/17/15.
//  Copyright (c) 2015 Eric Wang. All rights reserved.
//
#import "RegisterViewController.h"
#import "AppDelegate.h"
#import "UserData.h"
#import "AFNetworking.h"
#import "ProfileLoginControllerViewController.h"

@interface ProfileLoginControllerViewController ()<UITextFieldDelegate,CLLocationManagerDelegate>
@property(nonatomic,strong)RegisterViewController *regis;
- (IBAction)register:(id)sender;
@property(nonatomic,copy)NSString *token;
@property (weak, nonatomic) IBOutlet UIButton *rememberButton;
@property (weak, nonatomic) IBOutlet UIButton *resetButton;
- (IBAction)rememberPassword:(id)sender;
- (IBAction)resetPassWord:(id)sender;
@property (weak, nonatomic) IBOutlet UIImageView *refreshImageView;
@property (weak, nonatomic) IBOutlet UILabel *warningLabel;
@property (weak, nonatomic) IBOutlet UIButton *login;
- (IBAction)login:(id)sender;

- (IBAction)backToHome:(id)sender;
@property (weak, nonatomic) IBOutlet UITextField *textTop;
@property (weak, nonatomic) IBOutlet UIImageView *imageBottom;
@property (weak, nonatomic) IBOutlet UITextField *textBottom;

@property (weak, nonatomic) IBOutlet UIImageView *imageTop;
@end

@implementation ProfileLoginControllerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getDelegate];
    //self.imageTop.layer.borderColor = [UIColor red];
    // Do any additional setup after loading the view from its nib.
}




- (IBAction)login:(id)sender {
    
    if([self.textBottom.text isEqualToString:@""]||[self.textTop.text isEqualToString:@""])
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"警告" message:@"用户名或密码为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }else{
        
        self.refreshImageView.hidden = NO;
    
        CABasicAnimation* rotationAnimation;
        rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
        rotationAnimation.duration = 1.5;
        rotationAnimation.cumulative = YES;
        rotationAnimation.repeatCount = MAXFLOAT;
        
        [self.refreshImageView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
        
    NSString *string = [NSString stringWithFormat:@"http://localhost:8888/thinkphp_3.2.3/Home/QSBK/login?"];
        NSDictionary *para = @{@"user_count":self.textTop.text,@"user_pwd":self.textBottom.text};
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        [manager POST:string parameters:para success:^(AFHTTPRequestOperation *operation,id responseObject){
            
            NSDictionary *dictionary = (NSDictionary *)responseObject;
            NSLog(@"%@",dictionary);
            if([[dictionary objectForKey:@"err"] intValue]==0)
            {
                NSArray *contentDic = [dictionary objectForKey:@"user"];
                NSDictionary *userDic = [contentDic objectAtIndex:0];
                User *user = [[User alloc]init];
                user.last_visited_at = [userDic objectForKey:@"last_visite_at"];
                user.stater = [userDic objectForKey:@"stater"];
                user.email = [userDic objectForKey:@"email"];
                user.last_device = [userDic objectForKey:@"last_device"];
                user.role = [userDic objectForKey:@"role"];
                user.login = [userDic objectForKey:@"login"];
                user.token = [userDic objectForKeyedSubscript:@"token"];
                user.user_id = [userDic objectForKey:@"user_id"];
                user.icon = [userDic objectForKey:@"icon"];
                user.longitude = [userDic objectForKey:@"longitude"];
                user.latitude = [userDic objectForKey:@"latitude"];
                user.articleTotal = [userDic objectForKey:@"articleTotal"];
    
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.textBottom resignFirstResponder];
                    [self.textTop resignFirstResponder];
                   
                   AppDelegate *delegate = [UIApplication sharedApplication].delegate;
                    delegate.isSaveUserInfo = self.rememberButton.selected;
                    delegate.user=user;
                    if(self.rememberButton.selected)
                    {
                        NSData *userInfo = [NSKeyedArchiver archivedDataWithRootObject:user];
                        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                        [userDefaults setObject:userInfo forKey:@"userInfo"];
                        [userDefaults synchronize];
                    }
                    [self.refreshImageView.layer removeAllAnimations];
                    self.refreshImageView.hidden = YES;
                    if(self.delegate!=nil&&[self.delegate respondsToSelector:@selector(afterLoginSuccess:)])
                    {
                        [self.delegate afterLoginSuccess:[NSString stringWithFormat:@"欢迎回来，%@",user.login]];
                    }
                    [self dismissViewControllerAnimated:YES completion:nil];
                });
            }else{
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.refreshImageView.layer removeAllAnimations];
                    self.refreshImageView.hidden = YES;
                    UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"警告" message:@"用户名或密码错误!" delegate:nil cancelButtonTitle:@"重新填写" otherButtonTitles:nil, nil];
                    [alter show];
                });
                
            }
            
            
            
        }failure:^(AFHTTPRequestOperation *operation,NSError *error){
            
            NSLog(@"%@",error);
        }];
    }
}



- (IBAction)backToHome:(id)sender {
    [self.textTop resignFirstResponder];
    [self.textBottom resignFirstResponder];
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)getDelegate
{
    
    //button
//    self.rememberButton.imageView.
    [self.rememberButton setImage:[UIImage imageNamed:@"check_box_uncheck.png"] forState:UIControlStateNormal];
    [self.rememberButton setImage:[UIImage imageNamed:@"check_box_checked.png"] forState:UIControlStateSelected];
    //
    self.refreshImageView.hidden = YES;
    self.warningLabel.textColor = [UIColor colorWithRed:254/255.0 green:200/255.0 blue:5/255.0 alpha:1.0];
    //[self.login setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.textTop becomeFirstResponder];
     self.textTop.delegate = self;
    self.textBottom.delegate = self;
    self.textTop.layer.backgroundColor = [UIColor whiteColor].CGColor;
    self.textBottom.layer.backgroundColor = [UIColor whiteColor].CGColor;
    self.textBottom.secureTextEntry = YES;
    
    self.textBottom.alpha = 1.0;
    [self.textTop addTarget:self action:@selector(textBeginEnditing:)
           forControlEvents:UIControlEventEditingDidBegin];
    
    [self.textBottom addTarget:self action:@selector(textBeginEnditing:)
           forControlEvents:UIControlEventEditingDidBegin];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(void)textBeginEnditing:(UITextField *)textField
{
    if([textField isEqual:self.textTop])
    {
        self.imageTop.layer.borderWidth=2.5;
        self.imageTop.layer.borderColor = [UIColor colorWithRed:253/255.0 green:173/255.0 blue:20/255.0 alpha:1.0].CGColor;
        self.imageBottom.layer.borderWidth=2.5;
        self.imageBottom.layer.borderColor = [UIColor colorWithRed:120/255.0 green:120/255.0 blue:120/255.0 alpha:1.0].CGColor;
    }else{
        self.imageTop.layer.borderWidth=2.5;
        self.imageTop.layer.borderColor = [UIColor colorWithRed:120/255.0 green:120/255.0 blue:120/255.0 alpha:1.0].CGColor;
        self.imageBottom.layer.borderWidth=2.5;
        self.imageBottom.layer.borderColor = [UIColor colorWithRed:253/255.0 green:173/255.0 blue:20/255.0 alpha:1.0].CGColor;
        
    }
}
- (IBAction)rememberPassword:(id)sender {
    
    if(((UIButton *)sender).selected == YES)
    {
        ((UIButton *)sender).selected = NO;
    }else{
        ((UIButton *)sender).selected = YES;
    }
    
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    delegate.isSaveUserInfo = ((UIButton *)sender).selected;
}

- (IBAction)resetPassWord:(id)sender {
}

#pragma location delegate 


- (IBAction)register:(id)sender {
    
    self.regis = [[RegisterViewController alloc]initWithNibName:@"RegisterViewController" bundle:nil];
    [self presentViewController:self.regis animated:YES completion:nil];
}
@end
